/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hcbank.jpa.controllers;

import com.hcbank.jpa.controllers.exceptions.IllegalOrphanException;
import com.hcbank.jpa.controllers.exceptions.NonexistentEntityException;
import com.hcbank.jpa.controllers.exceptions.PreexistingEntityException;
import com.hcbank.jpa.controllers.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import com.hcbank.jpa.entities.AccountEntity;
import com.hcbank.jpa.entities.CustomerEntity;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author NHAHV
 */
public class CustomerEntityJpaController implements Serializable {

    public CustomerEntityJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(CustomerEntity customerEntity) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (customerEntity.getAccountEntityList() == null) {
            customerEntity.setAccountEntityList(new ArrayList<AccountEntity>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<AccountEntity> attachedAccountEntityList = new ArrayList<AccountEntity>();
            for (AccountEntity accountEntityListAccountEntityToAttach : customerEntity.getAccountEntityList()) {
                accountEntityListAccountEntityToAttach = em.getReference(accountEntityListAccountEntityToAttach.getClass(), accountEntityListAccountEntityToAttach.getId());
                attachedAccountEntityList.add(accountEntityListAccountEntityToAttach);
            }
            customerEntity.setAccountEntityList(attachedAccountEntityList);
            em.persist(customerEntity);
            for (AccountEntity accountEntityListAccountEntity : customerEntity.getAccountEntityList()) {
                CustomerEntity oldCustomerIdOfAccountEntityListAccountEntity = accountEntityListAccountEntity.getCustomerId();
                accountEntityListAccountEntity.setCustomerId(customerEntity);
                accountEntityListAccountEntity = em.merge(accountEntityListAccountEntity);
                if (oldCustomerIdOfAccountEntityListAccountEntity != null) {
                    oldCustomerIdOfAccountEntityListAccountEntity.getAccountEntityList().remove(accountEntityListAccountEntity);
                    oldCustomerIdOfAccountEntityListAccountEntity = em.merge(oldCustomerIdOfAccountEntityListAccountEntity);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findCustomerEntity(customerEntity.getId()) != null) {
                throw new PreexistingEntityException("CustomerEntity " + customerEntity + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(CustomerEntity customerEntity) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            CustomerEntity persistentCustomerEntity = em.find(CustomerEntity.class, customerEntity.getId());
            List<AccountEntity> accountEntityListOld = persistentCustomerEntity.getAccountEntityList();
            List<AccountEntity> accountEntityListNew = customerEntity.getAccountEntityList();
            List<String> illegalOrphanMessages = null;
            for (AccountEntity accountEntityListOldAccountEntity : accountEntityListOld) {
                if (!accountEntityListNew.contains(accountEntityListOldAccountEntity)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain AccountEntity " + accountEntityListOldAccountEntity + " since its customerId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<AccountEntity> attachedAccountEntityListNew = new ArrayList<AccountEntity>();
            for (AccountEntity accountEntityListNewAccountEntityToAttach : accountEntityListNew) {
                accountEntityListNewAccountEntityToAttach = em.getReference(accountEntityListNewAccountEntityToAttach.getClass(), accountEntityListNewAccountEntityToAttach.getId());
                attachedAccountEntityListNew.add(accountEntityListNewAccountEntityToAttach);
            }
            accountEntityListNew = attachedAccountEntityListNew;
            customerEntity.setAccountEntityList(accountEntityListNew);
            customerEntity = em.merge(customerEntity);
            for (AccountEntity accountEntityListNewAccountEntity : accountEntityListNew) {
                if (!accountEntityListOld.contains(accountEntityListNewAccountEntity)) {
                    CustomerEntity oldCustomerIdOfAccountEntityListNewAccountEntity = accountEntityListNewAccountEntity.getCustomerId();
                    accountEntityListNewAccountEntity.setCustomerId(customerEntity);
                    accountEntityListNewAccountEntity = em.merge(accountEntityListNewAccountEntity);
                    if (oldCustomerIdOfAccountEntityListNewAccountEntity != null && !oldCustomerIdOfAccountEntityListNewAccountEntity.equals(customerEntity)) {
                        oldCustomerIdOfAccountEntityListNewAccountEntity.getAccountEntityList().remove(accountEntityListNewAccountEntity);
                        oldCustomerIdOfAccountEntityListNewAccountEntity = em.merge(oldCustomerIdOfAccountEntityListNewAccountEntity);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = customerEntity.getId();
                if (findCustomerEntity(id) == null) {
                    throw new NonexistentEntityException("The customerEntity with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            CustomerEntity customerEntity;
            try {
                customerEntity = em.getReference(CustomerEntity.class, id);
                customerEntity.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The customerEntity with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<AccountEntity> accountEntityListOrphanCheck = customerEntity.getAccountEntityList();
            for (AccountEntity accountEntityListOrphanCheckAccountEntity : accountEntityListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This CustomerEntity (" + customerEntity + ") cannot be destroyed since the AccountEntity " + accountEntityListOrphanCheckAccountEntity + " in its accountEntityList field has a non-nullable customerId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(customerEntity);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<CustomerEntity> findCustomerEntityEntities() {
        return findCustomerEntityEntities(true, -1, -1);
    }

    public List<CustomerEntity> findCustomerEntityEntities(int maxResults, int firstResult) {
        return findCustomerEntityEntities(false, maxResults, firstResult);
    }

    private List<CustomerEntity> findCustomerEntityEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(CustomerEntity.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public CustomerEntity findCustomerEntity(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(CustomerEntity.class, id);
        } finally {
            em.close();
        }
    }

    public int getCustomerEntityCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<CustomerEntity> rt = cq.from(CustomerEntity.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
